package com.itheima.ssm.controller;

import com.itheima.ssm.domain.SysLog;
import com.itheima.ssm.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAop {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysLogService sysLogService;

    //获取当前时间
    private Date startTime;
    //获取访问的类
    private Class exeClass;
    //获取访问的方法的名称
    private Method exeMethod;

    /**
     * 前置通知，主要获取访问时间，访问的方法
     *
     * @param jp
     * @throws NoSuchMethodException
     */
    @Before("execution(* com.itheima.ssm.controller.*.*(..))")
    public void doBefore(JoinPoint jp) throws NoSuchMethodException {
        startTime = new Date();
        String methodName = jp.getSignature().getName();
        exeClass = jp.getTarget().getClass();
        //获取执行方法的参数
        Object[] args = jp.getArgs();
        if (args == null || args.length == 0) {//方法无参数
            exeMethod = exeClass.getMethod(methodName);
        } else {//有参方法.
            //将所有参数的类型存入一个数组中
            Class[] objectArgs = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                objectArgs[i] = args[i].getClass();
            }
            exeMethod = exeClass.getMethod(methodName, objectArgs);
        }
    }

    /**
     * 后置通知，获取其他日志信息,时长、ip、url...
     */
    @After("execution(* com.itheima.ssm.controller.*.*(..))")
    public void doAfter(JoinPoint jp) {
        //获取方法访问时长
        Long visitTime = new Date().getTime() - startTime.getTime();
        //获取访问的ip
        String ip = request.getRemoteAddr();
        //获取url
        String url="";
        if (exeClass != SysLogController.class) {
            //获取控制器类上的注解url
            RequestMapping classAnno = (RequestMapping) exeClass.getAnnotation(RequestMapping.class);
            if (classAnno != null) {
                RequestMapping methodAnno = (RequestMapping) exeMethod.getAnnotation(RequestMapping.class);
                if (methodAnno != null) {
                    url = classAnno.value()[0] + methodAnno.value()[0];
                }
            }
            //获取操作用户名
            SecurityContext context = SecurityContextHolder.getContext();
            String username = ((User)(context.getAuthentication().getPrincipal())).getUsername();

            SysLog sysLog = new SysLog();
            sysLog.setVisitTime(startTime);//访问时间
            sysLog.setExecutionTime(visitTime);//设置执行时长
            sysLog.setIp(ip);//设置访问ip
            sysLog.setUrl(url);//设置访问url
            sysLog.setMethod("[类名]"+exeClass.getName()+"[方法名]"+exeMethod.getName());//设置方法名
            sysLog.setUsername(username);//设置用户名

            sysLogService.save(sysLog);
        }
    }
}
